<?php
namespace app\common\library\mstching;
use app\common\model\WebSet;

/*
 * 飞鹅打印机驱动模块
 * 测试机型号：FP-V58W
*/
class Feie
{
	private $baseurl = 'http://api.feieyun.cn/Api/Open/';//接口路径
	private $appid = '';		
	private $appsecret = '';
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$values = WebSet::getItem('printer');
		$this->appid = $values['feie']['app_key'];
		$this->appsecret = $values['feie']['app_secret'];
	}
	
	/**
	* [打印订单接口 Open_printMsg]
	* @param  [string] $sn      [打印机编号sn]
	* @param  [string] $data 	[打印数据]
	* @param  [string] $times   [打印联数]
	* @return [string]          [接口返回值]
	*/
	public function printMsg($data ,$sn ,$times='1')
	{
		$content = $this->make_order_templet($data);//获取打印模板
		$msgInfo = $this->msgInfo();
		$msgInfo['apiname'] = 'Open_printMsg';
		$msgInfo['sn'] = $sn;
		$msgInfo['content'] = $content;
		$msgInfo['times'] = $times;
		$res = json_decode($this->http_post_json($msgInfo),true);
		if($res['ret']==0){
			return $res['data'];//返回订单打印任务编号
		}
		return false;
	}
	
	/**
	* [查询订单是否打印成功接口 Open_queryOrderState]
	* @param  [string] $orderid [调用打印机接口成功后,服务器返回的JSON中的编号 例如：123456789_20190919163739_95385649]
	* @return [string]          [接口返回值]
	*/
	public function queryOrderState($orderid){
		$msgInfo = $this->msgInfo();
		$msgInfo['apiname'] = 'Open_queryOrderState';
		$msgInfo['orderid'] = $orderid;
		$jsonStr = json_encode($msgInfo);
		$res = json_decode($this->http_post_json($jsonStr),true);
		if($res['ret']==0){
			return true;
		}
		return false;
	}
	
	/**
	* [批量添加打印机接口 Open_printerAddlist]
	* @param  [string] $printerContent [打印机的sn#key]
	* @return [string]                 [接口返回值]
	*/
	public function printerAddlist($printerContent){
		//$printerContent,编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)
		$msgInfo = $this->msgInfo();
		$msgInfo['apiname'] = 'Open_printerAddlist';
		$msgInfo['printerContent'] = $printerContent;
		$res = json_decode($this->http_post_json($msgInfo),true);
		if($res['ret']==0){
			return true;
		}
		return false;
	}
	
	/**
	* [批量删除打印机 Open_printerDelList]
	* @param  [string] $snlist [打印机编号，多台打印机请用减号“-”连接起来]
	* @return [string]         [接口返回值]
	*/
	public function printerDelList($snlist){
		$msgInfo = $this->msgInfo();
		$msgInfo['apiname'] = 'Open_printerDelList';
		$msgInfo['snlist'] = $snlist;
		$res = json_decode($this->http_post_json($msgInfo),true);
		if($res['ret']==0){
			return true;
		}
		return false;
	}
	
	/**
	* [修改打印机信息接口 Open_printerEdit]
	* @param  [string] $sn       [打印机编号]
	* @param  [string] $name     [打印机备注名称]
	* @param  [string] $phonenum [打印机流量卡号码,可以不传参,但是不能为空字符串]
	* @return [string]           [接口返回值]
	*/
	public function printerEdit($data){
		$msgInfo = $this->msgInfo();
		$msgInfo['apiname'] = 'Open_printerEdit';
		$msgInfo['sn'] = $data['uuid'];
		$msgInfo['name'] = $data['name'];
		$msgInfo['phone'] = $data['phone'];
		$jsonStr = json_encode($msgInfo);
		$res = json_decode($this->http_post_json($jsonStr),true);
		if($res['ret']==0){
			return true;
		}
		return false;
	}
	
	/**
	* [获取某台打印机状态接口 Open_queryPrinterStatus]
	* @param  [string] $sn [打印机编号]
	* @return [string]     [接口返回值]
	*/
	public function queryPrinterStatus($sn){
		$msgInfo = $this->msgInfo();
		$msgInfo['apiname'] = 'Open_queryPrinterStatus';
		$msgInfo['sn'] = $sn;
		$res = json_decode($this->http_post_json($msgInfo),true);
		if($res['ret']==0){
			$msg = '离线';
			if($res['data']=='在线，工作状态正常。'){
				$msg = '正常';
			}
			if($res['data']=='在线，工作状态不正常。'){
				$msg = '异常';
			}
			return $msg;
		}
		return false;
	}
	
	/**
	* 公共参数
	*/
	private function msgInfo(){
		$time = time();         //请求时间
		return $msgInfo = [
			'user'=>$this->appid,
			'stime'=>$time,
			'sig'=>$this->signature($time)
		];
	}
	
	/**
	* [signature 生成签名]
	* @param  [string] $time [当前UNIX时间戳，10位，精确到秒]
	* @return [string]       [接口返回值]
	*/
	private function signature($time){
		return sha1($this->appid . $this->appsecret . $time);//公共参数，请求公钥
	}
	
	
	//发送post请求
	/**
	 * PHP发送Json对象数据
	 * @return string
	 */
	private function http_post_json($data)
	{
		$data = http_build_query($data);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $this->baseurl);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/x-www-form-urlencoded',
				'Content-Length: ' . strlen($data)
			)
		);
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		return $response;
	}
	/**
	 * 制作订单模板
	 * $data 订单数据
	 * 58mm的机器,一行打印16个汉字,32个字母;
	 */
	private function make_order_templet($data)
	{
		/*
		 <BR> ：换行符
		 <CUT> ：切刀指令(主动切纸,仅限切刀打印机使用才有效果) 
		 <LOGO> ：打印LOGO指令(前提是预先在机器内置LOGO图片)
		 <PLUGIN> ：钱箱或者外置音响指令
		 <CB></CB>：居中放大
		 <B></B>：放大一倍
		 <C></C>：居中
		 <L></L>：字体变高一倍
		 <W></W>：字体变宽一倍
		 <QR></QR>：二维码（单个订单，最多只能打印一个二维码）
		 <RIGHT></RIGHT>：右对齐
		 <BOLD></BOLD>：字体加粗
		*/
		if($data['table_id']>10000){
			$content = '<CB># '.$data['table']['table_name'].' #</CB><BR>';
		}
		
		if($data['table_id']==1){
			$content = '<CB># 堂食'.$data['row_no'].'号 #</CB><BR>';
		}
		if($data['table_id']==2){
			$content = '<CB># 自取'.$data['row_no'].'号 #</CB><BR>';
			$content .= '到店时间:'.$data['arrive_time'].'<BR>';
		}
		if($data['table_id']==3){
			$content = '<CB># 外卖'.$data['row_no'].'号 #</CB><BR>';
		}
		$content .= '--------------------------------<BR>';
		$content .= '<C>'.$data['shop']['shop_name'].'</C><BR>';
		if($data['transaction_id']){
			$content .= '<C>-- 微信支付 --</C><BR>';
		}else{
			$content .= '<C>-- 余额支付 --</C><BR>';
		}
		
		$content .= '支付时间:'.date("Y-m-d H:i:s",$data['pay_time']).'<BR>';
		$content .= '--------------------------------<BR>';
		$content .= '名称             单价 数量 金额 <BR>';//字符占位数量16+6+4+6
		//循环拼接打印模板
		for ($i = 0; $i < sizeof($data['goods']); $i++) {
				$goods_attr = '';
				if($data['goods'][$i]['goods_attr']){
					$goods_attr = ':'+$data['goods'][$i]['goods_attr'];
				}
				$goods_name = $data['goods'][$i]['goods_name'].$goods_attr;//产品名字
				$goods_price = $data['goods'][$i]['goods_price'];	//产品单价
				$total_num = $data['goods'][$i]['total_num'];	//产品数量
				$total_price = $data['goods'][$i]['total_price'];//产品总价格
				
				//设置名称字符长度
				$lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
				for($n=$lan;$n<16;$n++){
					$goods_name .= ' ';
				}
				//设置单价字符长度
				$lan = mb_strlen($goods_price,'utf-8');
				for($n=$lan;$n<6;$n++){
					$goods_price .= ' ';
				}
				//设置单价字符长度
				$lan = mb_strlen($total_num,'utf-8');
				for($n=$lan;$n<4;$n++){
					$total_num .= ' ';
				}
				//设置单价字符长度
				$lan = mb_strlen($total_price,'utf-8');
				for($n=$lan;$n<6;$n++){
					$total_price .= ' ';
				}
				$content .= $goods_name.$goods_price.$total_num.$total_price.'<BR>';
		}
		$content .= '--------------------------------<BR>';		
		$content .= '商品数量：'.$i.'<BR>';
		$content .= '商品金额：￥'.$data['total_price'].'元<BR>';
		if($data['table_id']==3){
			$content .= '配送费用：￥'.$data['express_price'].'元<BR>';
		}
		if($data['table_id']==2 OR $data['table_id']==3){
			$content .= '餐盒费用：￥'.$data['pack_price'].'元<BR>';
		}
		if($data['table_id']>10000){
			$content .= '餐具调料：￥'.$data['ware_price'].'元<BR>';
		}
		$content .= '优惠金额：￥'.$data['activity_price'].'元<BR>';
		$content .= '实付金额：￥'.$data['pay_price'].'元<BR>';
		if($data['flavor']){
			$content .= '口味要求：￥'.$data['flavor'].'元<BR>';
		}
		if($data['message']){
			$content .= '顾客留言：￥'.$data['message'].'元<BR>';
		}
		if($data['table_id']>10000){
			$content .= '<CB># '.$data['table']['table_name'].' # 完</CB><BR>';
		}
		if($data['table_id']==1){
			$content .= '<CB># 堂食'.$data['row_no'].'号 # 完</CB><BR>';
		}
		if($data['table_id']==2){
			$content .= '<CB># 自取'.$data['row_no'].'号 # 完</CB><BR>';
		}
		if($data['table_id']==3){
			$content .= '<CB># 外卖'.$data['row_no'].'号 # 完</CB><BR>';
		}
		$content .= '<BR><BR><CUT>';
		return $content;
	}
}